const router = require('koa-router')()
const mongoose = require('mongoose')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const { pageQuery } = require('../common/index')

const successResponse = (code, msg, data) => {
    return { code, msg, data }
}

router.prefix('/api/admin')

router
    // 登录校验
    .get('/adminIsLogin', async ctx => {
        let token = ctx.req.headers.admintoken
        if (token === undefined || token === '0') {
            ctx.body = successResponse(401, '未登录', null)
        } else {
            try {
                let tokenInfo = jwt.verify(token, 'zzh', {
                    algorithm: 'HS256'
                })
                if (tokenInfo.time < new Date().getTime()) {
                    ctx.body = successResponse(401, '登录过期', null)
                } else {
                    const AdminlModel = mongoose.model('Admin')
                    let result = await AdminlModel.findOne({ adminName: tokenInfo.adminName })
                    ctx.body = successResponse(200, '已登录', result)
                } 
            } catch (err) {
                console.log('/adminIsLogin : ', err)
                ctx.body = successResponse(503, 'err', null)
            }
        }
    })
    // 管理员登录
    .post('/adminLogin', async ctx => {
        const AdminlModel = mongoose.model('Admin')
        let params = JSON.parse(JSON.stringify(ctx.request.body))
        params.adminPassword = md5(params.adminPassword)
        await AdminlModel.findOne({ adminName: params.adminName, adminPassword: params.adminPassword }).then(async res => {
            if (res) {
                const token = jwt.sign({
                    time: new Date().getTime() + 1000 * 60 * 5,
                    adminName: params.adminName
                }, 'zzh', { algorithm: 'HS256' })
                await AdminlModel.update({ adminName: params.adminName }, { adminToken: token })
                let result = await AdminlModel.findOne({ adminName: params.adminName })
                ctx.body = successResponse(200, '登录成功', result)
            } else {
                ctx.body = successResponse(503, '账号或密码错误', null)
            }
        }).catch(err => {
            console.log('/adminLogin : ', err)
            ctx.body = successResponse(503, '登陆失败', null)
        })
    })
    // 获取管理员列表
    .get('/getAdminList', async ctx => {
        const AdminlModel = mongoose.model('Admin')
        var page = ctx.query.page || 1
        try {
            var res = await pageQuery(page, 10, AdminlModel, '', {}, {
                created_time: 'desc'
            })
            ctx.body = successResponse(200, 'success', res)
        } catch (err) {
            ctx.body = successResponse(503, 'error', null)
        }
    })
    // 新增管理员
    .post('/addAdminList', async ctx => {
        const AdminlModel = mongoose.model('Admin')
        let params = JSON.parse(JSON.stringify(ctx.request.body))
        params.adminPassword = md5(params.adminPassword)
        var adminlModel = new AdminlModel(params)
        try {
            await adminlModel.save()
            ctx.body = successResponse(200, '添加成功', null)
        } catch (err) {
            ctx.body = successResponse(503, '添加失败', null)
        }
    })
    // 修改管理员
    .put('/updateAdminList', async ctx => {
        const AdminlModel = mongoose.model('Admin')
        let params = JSON.parse(JSON.stringify(ctx.request.body))
        try {
            await AdminlModel.findOne({ _id: params._id }).then(res => {
                if (res.adminPassword !== params.adminPassword) {
                    params.adminPassword = md5(params.adminPassword)
                }
            })
            await AdminlModel.updateOne({ _id: params._id }, params)
            ctx.body = successResponse(200, '修改成功', null)
        } catch (err) {
            console.log('/updateAdminList : ', err)
            ctx.body = successResponse(503, '修改失败', null)
        }
    })
    // 删除管理员
    .delete('/delAdminList', async ctx => {
        const AdminlModel = mongoose.model('Admin')
        let ids = ctx.query.ids
        ids = ids.split(',')
        try {
            for (let i = 0; i < ids.length; i++ ) {
                await AdminlModel.remove({ _id: ids[i] })
            }
            ctx.body = successResponse(200, '删除成功', null)
        } catch (err) {
            ctx.body = successResponse(503, '删除失败', err)
        }
    })

module.exports = router
